<template>
    <q-page class="post-detail-page q-pa-md" v-if="threadData">
        <q-header elevated class="text-white" :style="setTransColor()">
            <q-toolbar>
                <q-btn flat round dense icon="arrow_back" @click="goBack" />

                <q-avatar size="32px" class="q-ml-sm">
                    <img v-if="threadData.thread.User && threadData.thread.User.avatar_urls.h"
                        :src="threadData.thread.User.avatar_urls.h" :alt="threadData.thread.User.username">
                    <q-icon v-else name="person" size="48px" color="primary" />
                </q-avatar>

                <q-toolbar-title class="ellipsis">
                    <span style="font-size:16px">{{ threadData.thread.title }}</span>
                </q-toolbar-title>

                <q-btn flat round dense icon="more_vert">
                    <q-menu flat>
                        <q-list style="min-width: 100px">
                            <q-item clickable v-close-popup @click="sharePost">
                                <q-item-section avatar>
                                    <q-icon name="share" />
                                </q-item-section>
                                <q-item-section>分享</q-item-section>
                            </q-item>
                            <q-item clickable v-close-popup @click="reportPost">
                                <q-item-section avatar>
                                    <q-icon name="report" />
                                </q-item-section>
                                <q-item-section>举报</q-item-section>
                            </q-item>
                            <q-item clickable v-close-popup @click="blockUser">
                                <q-item-section avatar>
                                    <q-icon name="block" />
                                </q-item-section>
                                <q-item-section>屏蔽用户</q-item-section>
                            </q-item>
                        </q-list>
                    </q-menu>
                </q-btn>
            </q-toolbar>
        </q-header>

        <div style="padding-bottom:56px;">
            <div class="post-header row items-center justify-between q-mb-md">
                <div class="row items-center">
                    <q-avatar size="48px">
                        <img v-if="threadData.thread.User && threadData.thread.User.avatar_urls.h"
                            :src="threadData.thread.User.avatar_urls.h" :alt="threadData.thread.User.username">
                        <q-icon v-else name="person" size="48px" color="primary" />
                    </q-avatar>
                    <div class="column q-ml-sm q-mt-xs">
                        <div class="row items-center">
                            <div>{{ threadData.thread.username }}</div>
                            <q-chip color="primary" class="text-body2" text-color="white" dense
                                v-if="threadData.thread.User">{{ threadData.thread.User.user_title }}</q-chip>
                        </div>
                        <div class="col">
                            <div class="text-caption text-grey-6">
                                {{ formatTime(threadData.thread.post_date) }}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="post-actions">
                    <q-btn :color="post.isFollowing ? 'grey-5' : 'primary'" :label="post.isFollowing ? '已关注' : '关注'"
                        size="sm" class="q-mr-sm" @click="toggleFollow" />
                </div>
            </div>
            <div class="text-h6 text-weight-medium q-mb-md">{{ threadData.thread.title }}</div>
            <div flat class="post-content q-mb-lg" v-if="threadData.first_post">
                <div class="post-content-inner">
                    <div class="text-body1" v-html="threadData.first_post.message_parsed"></div>
                </div>

                <div class="text-grey-6 row justify-around q-mt-sm">
                    <q-btn flat size="sm" :color="post.isLiked ? 'red' : 'grey-6'" @click="toggleLike">
                        <q-icon :name="post.isLiked ? 'favorite' : 'favorite_border'" class="q-mr-xs" />
                        {{ threadData.first_post.reaction_score }}
                    </q-btn>
                    <q-btn flat size="sm" color="grey-6">
                        <q-icon name="chat_bubble_outline" class="q-mr-xs" />
                        {{ threadData.thread.reply_count }}
                    </q-btn>
                    <q-btn flat size="sm" color="grey-6" @click="sharePost">
                        <q-icon name="share" class="q-mr-xs" />
                        分享
                    </q-btn>
                </div>
            </div>

            <div class="replies-section">
                <div class="row items-center justify-between">
                    <div class="text-body2">
                        回复 ({{ threadData.thread.reply_count }})
                    </div>

                    <div v-if="threadData.thread.reply_count > 20">
                        <q-btn-toggle v-model="reply_type" toggle-color="primary" flat :options="[
                            { label: '正序', value: 'asc' },
                            { label: '倒序', value: 'desc' }
                        ]" @update:model-value="onReplyTypeChange" />
                    </div>
                </div>

                <q-infinite-scroll @load="loadMorePosts" :offset="250" :key="infiniteScrollKey">
                    <q-list separator>
                        <q-item v-for="(reply, index) in allPosts" :key="reply.post_id" class="reply-item"
                            style="padding:6px">
                            <q-item-section avatar top>
                                <q-avatar size="40px">
                                    <img v-if="reply.User && reply.User.avatar_urls.h" :src="reply.User.avatar_urls.h"
                                        :alt="reply.User.username">
                                    <q-icon v-else name="person" size="48px" color="primary" />
                                </q-avatar>
                            </q-item-section>

                            <q-item-section>
                                <div class="reply-header row items-center q-mb-xs">
                                    <span class="text-weight-medium">{{ reply.username }}</span>
                                    <q-chip color="primary" class="text-body2" text-color="white" dense
                                        v-if="reply.user_id == threadData.thread.user_id">楼主</q-chip>
                                    <span class="text-caption text-grey-6 q-ml-sm">
                                        #{{ getFloorNumber(reply, index) }}楼 · {{ formatTime(reply.post_date) }}
                                    </span>
                                    <q-space />
                                    <q-btn flat round size="sm" icon="more_vert">
                                        <q-menu>
                                            <q-list style="min-width: 100px">
                                                <q-item clickable v-close-popup @click="replyToReply(reply)">
                                                    <q-item-section>回复</q-item-section>
                                                </q-item>
                                                <q-item clickable v-close-popup @click="reportReply(reply)">
                                                    <q-item-section>举报</q-item-section>
                                                </q-item>
                                            </q-list>
                                        </q-menu>
                                    </q-btn>
                                </div>

                                <div class="reply-content text-body2 q-mb-sm">
                                    <div v-html="formatReplyMessage(reply.message)"></div>
                                </div>

                                <div class="reply-actions">
                                    <q-btn flat size="sm" :color="reply.isLiked ? 'red' : 'grey-6'"
                                        @click="toggleReplyLike(reply)">
                                        <q-icon :name="reply.isLiked ? 'favorite' : 'favorite_border'"
                                            class="q-mr-xs" />
                                        {{ reply.reaction_score }}
                                    </q-btn>
                                    <q-btn flat size="sm" color="grey-6" @click="replyToReply(reply)">
                                        <q-icon name="reply" class="q-mr-xs" />
                                        回复
                                    </q-btn>
                                </div>
                            </q-item-section>
                        </q-item>
                    </q-list>

                    <template v-slot:loading>
                        <div class="row justify-center q-my-md">
                            <q-spinner-dots color="primary" size="40px" />
                        </div>
                    </template>
                </q-infinite-scroll>
            </div>
        </div>

        <transition name="fade">
            <div v-show="showMoreMenu" class="menu-backdrop-overlay" @click="hideMoreOptions"></div>
        </transition>

        <q-slide-transition>
            <div v-show="showMoreMenu" class="more-options-panel">
                <div class="menu-content">
                    <div class="menu-grid">
                        <div class="menu-item" @click="selectImage">
                            <q-icon name="image" size="24px" color="primary" />
                            <span>图片</span>
                        </div>
                        <div class="menu-item" @click="takePhoto">
                            <q-icon name="camera_alt" size="24px" color="primary" />
                            <span>拍照</span>
                        </div>
                        <div class="menu-item" @click="selectFile">
                            <q-icon name="attach_file" size="24px" color="primary" />
                            <span>文件</span>
                        </div>
                    </div>
                </div>
            </div>
        </q-slide-transition>

        <q-footer :style="setTransColor()">
            <q-toolbar class="input-toolbar">
                <q-btn flat round dense icon="add" @click="toggleMoreOptions" :class="{ 'rotated': showMoreMenu }" />

                <q-input v-model="inputMessage" ref="inputRef" outlined dense placeholder="写下你的回复..." dark
                    class="input-field" autogrow :max-height="100" @keyup.enter="sendReply" @focus="scrollToBottom">
                    <template v-slot:append>
                        <q-btn flat round dense icon="sentiment_satisfied_alt" color="white" @click="showEmojiPicker" />
                    </template>
                </q-input>

                <q-btn v-if="inputMessage.trim()" round color="primary" icon="send" size="sm" class="send-btn q-ml-sm"
                    @click="sendReply" />
            </q-toolbar>
        </q-footer>

        <input ref="imageInput" type="file" accept="image/*" multiple style="display: none"
            @change="handleImageSelect" />
        <input ref="videoInput" type="file" accept="video/*" style="display: none" @change="handleVideoSelect" />
        <input ref="fileInput" type="file" style="display: none" @change="handleFileSelect" />
    </q-page>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useQuasar } from 'quasar'
import { setTransColor, formatTime } from 'src/utils/common'
import { formatReplyMessage } from 'src/utils/threadParse'
import { getThreadDetail } from 'src/utils/api'
import { postReply } from 'src/utils/writeapi'
// Quasar 实例
const $q = useQuasar()
const router = useRouter()
const route = useRoute()

// Data
const threadData = ref(null)
const loading = ref(true)
const inputMessage = ref('')
const submitting = ref(false)
const showMoreMenu = ref(false)
const imageInput = ref(null)
const videoInput = ref(null)
const fileInput = ref(null)
const inputRef = ref(null)
const reply_type = ref('asc')

// 分页状态
const currentPage = ref(1)
const hasMorePosts = ref(true)
const paginationInfo = ref(null)
const infiniteScrollKey = ref(0) // 用于重置无限滚动组件

// 存储所有回复的数组
const allPosts = ref([])

onMounted(async () => {
    await loadThreadData()
})

const loadThreadData = async () => {
    try {
        loading.value = true
        // 重置分页状态
        currentPage.value = 1
        allPosts.value = []

        const data = await getThreadDetail(route.params.id, {
            with_posts: true,
            with_first_post: true,
            page: currentPage.value
        })

        threadData.value = data
        paginationInfo.value = data.pagination

        // 处理回复数据
        if (data.posts && data.posts.length > 0) {
            // 移除第一个帖子（如果包含在posts中）
            let posts = data.posts
            if (data.first_post && posts.length > 0 && posts[0].post_id === data.first_post.post_id) {
                posts = posts.slice(1)
            }
            allPosts.value = posts
        }

        // 设置分页状态
        if (data.pagination) {
            hasMorePosts.value = data.pagination.current_page < data.pagination.last_page
        } else {
            hasMorePosts.value = false
        }

    } catch (error) {
        console.error('加载帖子详情失败:', error)
        $q.notify({ type: 'negative', message: '加载失败，请稍后重试' })
    } finally {
        loading.value = false
    }
}

// 正序倒序切换处理
const onReplyTypeChange = async (newType) => {
    try {
        loading.value = true

        // 清空现有数据
        allPosts.value = []

        // 重置无限滚动组件
        infiniteScrollKey.value++

        if (newType === 'desc') {
            // 倒序：从最后一页开始
            currentPage.value = paginationInfo.value?.last_page || 1
        } else {
            // 正序：从第一页开始
            currentPage.value = 1
        }

        // 加载第一批数据
        const data = await getThreadDetail(route.params.id, {
            with_posts: true,
            page: currentPage.value
        })

        if (data.posts && data.posts.length > 0) {
            let posts = data.posts
            // 移除第一个帖子（如果包含在posts中）
            if (threadData.value.first_post && posts.length > 0 && posts[0].post_id === threadData.value.first_post.post_id) {
                posts = posts.slice(1)
            }

            if (newType === 'desc') {
                // 倒序：需要将API返回的正序数据反转
                allPosts.value = posts.reverse()
            } else {
                // 正序：直接使用
                allPosts.value = posts
            }
        }

        // 更新分页状态
        if (newType === 'desc') {
            hasMorePosts.value = currentPage.value > 1
        } else {
            hasMorePosts.value = data.pagination ? data.pagination.current_page < data.pagination.last_page : false
        }

    } catch (error) {
        console.error('切换排序失败:', error)
        $q.notify({ type: 'negative', message: '切换排序失败，请稍后重试' })
    } finally {
        loading.value = false
    }
}

// 无限滚动加载更多回复
const loadMorePosts = async (index, done) => {
    // 停止条件
    if (!hasMorePosts.value) {
        done(true)
        return
    }

    try {
        let nextPage

        if (reply_type.value === 'desc') {
            // 倒序：页码递减
            nextPage = currentPage.value - 1
            if (nextPage < 1) {
                hasMorePosts.value = false
                done(true)
                return
            }
        } else {
            // 正序：页码递增
            nextPage = currentPage.value + 1
        }

        const data = await getThreadDetail(route.params.id, {
            with_posts: true,
            page: nextPage
        })

        if (data.posts && data.posts.length > 0) {
            let posts = data.posts
            // 移除第一个帖子（如果包含在posts中）
            if (threadData.value.first_post && posts.length > 0 && posts[0].post_id === threadData.value.first_post.post_id) {
                posts = posts.slice(1)
            }

            if (reply_type.value === 'desc') {
                // 倒序：将新数据反转后添加到数组末尾
                allPosts.value.push(...posts.reverse())
                hasMorePosts.value = nextPage > 1
            } else {
                // 正序：直接添加到数组末尾
                allPosts.value.push(...posts)
                hasMorePosts.value = data.pagination ? data.pagination.current_page < data.pagination.last_page : false
            }

            currentPage.value = nextPage
        } else {
            hasMorePosts.value = false
        }

        done(!hasMorePosts.value)
    } catch (error) {
        console.error('加载更多回复失败:', error)
        hasMorePosts.value = false
        done(true)
    }
}

// 计算楼层号
const getFloorNumber = (reply, index) => {
    if (reply_type.value === 'desc') {
        // 倒序：楼层号需要根据总数计算
        const totalReplies = threadData.value?.thread?.reply_count || 0
        return totalReplies - index + 1
    } else {
        // 正序：楼层号就是索引+2（因为第一楼是主贴）
        return index + 2
    }
}

// 以下是原有方法，保持不变
const post = reactive({
    isLiked: false,
    isFollowing: false,
})

const goBack = () => {
    router.back()
}

const scrollToBottom = () => {
    nextTick(() => {
        window.scrollTo({
            top: document.body.scrollHeight,
            behavior: 'smooth'
        })
    })
}

const sendReply = async () => {
    if (!inputMessage.value.trim()) return

    submitting.value = true
    try {
        const res = await postReply({
            thread_id: route.params.id,
            message: inputMessage.value,
            parent_id: 0
        })
        if (res.success) {
            $q.notify({ message: '回复发布成功', color: 'positive' })
            inputMessage.value = ''
            await loadThreadData() // 重新加载数据以显示新回复
            scrollToBottom()
        }
    } catch (error) {
        console.error('回复失败:', error)
        $q.notify({ message: '回复失败', color: 'negative' })
    } finally {
        submitting.value = false
    }
}

const toggleFollow = () => {
    post.isFollowing = !post.isFollowing
    // 添加API调用来关注/取消关注用户
}

const toggleLike = () => {
    post.isLiked = !post.isLiked
    threadData.value.first_post.reaction_score += post.isLiked ? 1 : -1
    // 添加API调用来点赞/取消点赞帖子
}

const sharePost = () => {
    $q.notify({ message: '分享功能', color: 'info', position: 'top' })
}

const reportPost = () => {
    $q.notify({ message: '举报功能', color: 'warning', position: 'top' })
}

const blockUser = () => {
    $q.notify({ message: '屏蔽用户功能', color: 'warning', position: 'top' })
}

const toggleReplyLike = (reply) => {
    reply.isLiked = !reply.isLiked
    reply.reaction_score += reply.isLiked ? 1 : -1
    // 添加API调用来点赞/取消点赞回复
}

const replyToReply = (reply) => {
    inputMessage.value = `[QUOTE="${reply.username}, post: ${reply.post_id}, member: ${reply.user_id}"]${reply.message}[/QUOTE] `
    nextTick(() => {
        inputRef.value?.focus()
    })
}

const reportReply = (reply) => {
    $q.notify({
        message: `举报 ${reply.username} 的回复`,
        color: 'warning',
        position: 'top'
    })
}

// 更多选项菜单方法
const toggleMoreOptions = () => {
    showMoreMenu.value = !showMoreMenu.value
}
const hideMoreOptions = () => {
    showMoreMenu.value = false
}
const selectImage = () => {
    hideMoreOptions()
    imageInput.value?.click()
}
const takePhoto = () => {
    hideMoreOptions()
    $q.notify({ message: '拍照功能开发中...', color: 'info' })
}
const selectFile = () => {
    hideMoreOptions()
    fileInput.value?.click()
}
const showEmojiPicker = () => {
    $q.notify({ message: '表情功能开发中...', color: 'info' })
}

// 文件处理方法
const handleImageSelect = () => { /* ... */ }
const handleVideoSelect = () => { /* ... */ }
const handleFileSelect = () => { /* ... */ }


</script>

<style lang="scss" scoped>
.post-detail-page {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.post-actions {
    flex-shrink: 0;
}

.reply-header {
    margin-bottom: 8px;
}

.reply-content {
    line-height: 1.5;
    word-break: break-word;
}

.reply-actions {
    display: flex;
    gap: 8px;
}

// Footer input styles
.input-toolbar {
    padding: 8px 16px;
    align-items: flex-end;
}

.input-field {
    flex: 1;
    margin: 0 8px;
}

.input-field :deep(.q-field__control) {
    border-radius: 20px;
}

.send-btn {
    min-width: 40px;
    height: 40px;
}

.rotated {
    transform: rotate(45deg);
    transition: transform 0.2s ease;
}

/* More options menu styles */
.menu-backdrop-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 5999;
}

.more-options-panel {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 53px;
    z-index: 6000;
}

.menu-content {
    background: white;
    border-radius: 16px 16px 0 0;
    padding: 20px;
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
}

.menu-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
}

.menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px 12px;
    border-radius: 12px;
    background-color: #f5f5f5;
    cursor: pointer;
    transition: all 0.2s ease;
}

.menu-item:hover {
    background-color: #e8f4fd;
    transform: translateY(-2px);
}

.menu-item:active {
    transform: translateY(0);
    background-color: #d1ecf1;
}

.menu-item span {
    margin-top: 8px;
    font-size: 12px;
    color: #666;
    font-weight: 500;
}

/* Transitions */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

/* Dark mode adaptations */
.body--dark .menu-content {
    background-color: #2a2a2a;
}

.body--dark .menu-item {
    background-color: #3a3a3a;
}

.body--dark .menu-item:hover {
    background-color: #4a4a4a;
}

.body--dark .menu-item span {
    color: #ccc;
}
</style>

<style lang="scss" scoped>
.post-content-inner {
    :deep(img) {
        max-width: 100%;
        border-radius: 8px;
        height: auto;
    }
}

.reply-content {
    :deep(img) {
        width: 100%;
    }

    :deep(.reply-quote) {
        background-color: #f5f5f5;
        border-left: 4px solid #dcdcdc;
        padding: 10px 15px;
        margin: 10px 0;
        border-radius: 0 4px 4px 0;
        color: #666;
    }

    :deep(.reply-quote-header) {
        font-size: 0.9em;
        margin-bottom: 6px;
    }

    :deep(.reply-quote-content) {
        font-size: 0.95em;
        font-style: italic;
    }
}

.body--dark .reply-content {
    :deep(.reply-quote) {
        background-color: #333;
        color: #fff;
    }
}
</style>